package com.lemon.utils;

import io.netty.util.CharsetUtil;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


/**
 * @author lenomSeven 1337857379@qq.com
 * @date 2020/10/7
 */
public class ZKUtil {
    private static final Logger logger = LoggerFactory.getLogger(ZKUtil.class);

    private ZooKeeper zooKeeper;

    public ZKUtil(String zkAdds) throws IOException {
        zooKeeper = new ZooKeeper(zkAdds, 10000, new MyWatched());
    }


    public String getDate(String path) throws KeeperException, InterruptedException {
        String data = new String(zooKeeper.getData(path, null, new Stat()), CharsetUtil.UTF_8);
        return data;
    }

    public void updataNode(String path, String data) {
        updataNode(path, data, CreateMode.PERSISTENT);
    }

    public void updataNode(String path, String data, CreateMode mode) {
        try {
            byte[] dataBytes = data.getBytes();
            //String res;
            //CreateMode:（1）PERSISTENT：持久；（2）PERSISTENT_SEQUENTIAL：持久顺序；（3）EPHEMERAL：临时；（4）EPHEMERAL_SEQUENTIAL：临时顺序。
            if (null==zooKeeper.exists(path, false)) {
                //不存在节点，则新建
                zooKeeper.create(path, dataBytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, mode);
            }
            else{
                Stat stat = new Stat();
                zooKeeper.setData(path, dataBytes, -1);
            }
            String newData = new String(zooKeeper.getData(path, null, new Stat()));
            logger.info("new data is:{}", newData);
        } catch (Exception e) {
            logger.error("updataNode error", e);
        }
    }

    class MyWatched implements Watcher {

        @Override
        public void process(WatchedEvent watchedEvent) {
            logger.info("process" + watchedEvent.getType().name() + " " + watchedEvent.getPath() + " " + watchedEvent.getState().name());
        }
    }

    public void close(){
        if (zooKeeper != null) {
            try {
                zooKeeper.close();
            } catch (InterruptedException e) {
                logger.error("zooKeeper object close error.");
            }
        }
    }


}